package com.imooc.authorization.context;

import com.imooc.authorization.entity.Function;
import com.imooc.authorization.entity.Role;
import com.imooc.authorization.service.FunctionService;
import com.imooc.authorization.service.RoleService;
import com.sun.xml.internal.bind.v2.model.core.ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/18.
 */

@Service
public class NativeCache {

    private Map<Long,Function> functionMap=new HashMap<>();

    private Map<Long,List<Role>> userRoleMap=new HashMap<>();

    @Autowired private FunctionService functionService;


    //初始化对象时，首选调用的方法
    @PostConstruct
    public void init(){
        List<Function> functionList=functionService.getAllFunctions();
        functionList.forEach((function -> functionMap.put(function.getId(),function)));

    }




    public List<Function> getFunctions() {

        if(functionMap.isEmpty()){
            init();
        }
        return new ArrayList<>(functionMap.values());
    }

    public void addFunction(Function function){
        functionMap.put(function.getId(),function);
    }

    public void replaceFunction(Function function){

        if(functionMap.containsKey(function.getId())){
           functionMap.remove(function.getId());
            functionMap.put(function.getId(),function);

        }
    }

    public void removeFunction(Long functionId){

        if(functionMap.containsKey(functionId)){
            userRoleMap.remove(functionId);
        }
    }

    public void setRoles(Long userId,List<Role> roles){

        userRoleMap.put(userId, roles);
    }

    public Function getFunction(Long id){

        return functionMap.get(id);
    }

    public List<Role> getRoles(Long userId){

        return userRoleMap.get(userId);
    }
}
